package GUI;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import CommonGui.ButtonColumn;
import CommonGui.MyTableModelForKitchen;
import DataObjects.Fire;
import DataObjects.Submit;
import Messages.MessageGetFiredRecipes;
import Messages.MessageGetFiredRecipesReply;
import Messages.MessageSavingReply;
import Messages.MessageSubmitFire;

public class PfKitchen extends JPanel implements TableModelListener {

	private MainMenu mainMenu;
	private JPanel thisPanel;
	private MessageGetFiredRecipesReply result2;
	private Dimension screenSize;
	private int x;
	private int y;	
	private Vector<Fire> fires;
	private Vector<Vector<String>> firesVec;
	private MyTableModelForKitchen dtm;
	private JTable tbl;
	private Vector<ButtonForFire> vecButtons;
	private JComboBox comboBox;
	private int threadFlag=1;                      // we will check it in thread
	
	public PfKitchen (MainMenu mm)
	{
		super();
		this.thisPanel=this;
		this.mainMenu=mm;
		screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		x=screenSize.width;
		y=screenSize.height;
		this.setLayout(null);
		this.setBackground(new Color(255, 222, 173));
		
	
		
		
		MessageGetFiredRecipes msg=new MessageGetFiredRecipes();				
					
		try {
			mainMenu.ms.client.sendToServer(msg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			result2 = (MessageGetFiredRecipesReply)mainMenu.ms.client.GetMessage();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
				
		Thread fireStatus =new Thread(new FireStatus(this));
		fireStatus.setDaemon(true);
		fireStatus.start();
		fires=result2.getFires();
		initialize();		
	}
	
	
	private void initialize()
	{	JPanel tablePanel=getTablePanel();
		tablePanel.setBounds(x/1000,10*y/30, 10*x/12, 10*y/20);
		
		JPanel scheemPanel=getScheemPanel();
		scheemPanel.setBounds(x/1000, y/1000, x,10*y/30);
		
		JPanel optionsPanel=getOptionsPanel();
		optionsPanel.setBounds(10*x/12, 10*y/30, 10*x/60, 10*y/20);
		this.add(tablePanel);
		this.add(scheemPanel);
		this.add(optionsPanel);
	}
	
	
	private JPanel getScheemPanel()
	{
		JPanel scheemPanel=new JPanel();
		scheemPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "שולחנות", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(0, 0, 0)));

		vecButtons=new Vector<ButtonForFire>();
		GridLayout grid =new GridLayout(2, 0, 7, 7);
		scheemPanel.setLayout(grid);
		
		for(int i=0; i<20;i++)
		{
		ButtonForFire button=new ButtonForFire(Integer.toString(i+1),mainMenu);
		button.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				
				
				
				 
				
			}
		});
		scheemPanel.add(button);
		vecButtons.add(button);
		}
		return scheemPanel;
	}
	
	
	
	
	
	
	private JPanel getTablePanel()
	{
		JPanel tblPanel=new JPanel() ;
		tblPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "ניהול הזמנות", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(0, 0, 0)));
		tblPanel.setLayout(new BorderLayout());
		Vector <String> tblheader=new Vector<String>();	
		tblheader.add("Button");
		tblheader.add("מס שולחן");
		tblheader.add("מנה");
		tblheader.add("תוספת");
		tblheader.add("רוטב");
		tblheader.add("מידת עשייה");
		tblheader.add("הערות");
		tblheader.add("שם המלצר");
		tblheader.add("זמן המתנה");
		tblheader.add("מס' הזמנה");
		tblheader.add("כמות");
	
		
		Vector<Vector> vecFires=vecFiresToVecVec(fires);
		DefaultTableModel dftm=new DefaultTableModel(vecFires,tblheader);
		dtm=new MyTableModelForKitchen(vecFires,tblheader);	 		
		tbl = new JTable(dtm);
		
				
		tbl.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		tbl.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
		tbl.setFont(new Font("David", Font.BOLD,15));
		tbl.getTableHeader().setFont( new Font( "Arial" , Font.BOLD, 15 ));
		tbl.getTableHeader().setBackground(new Color(173,216,230));
		tbl.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); 
	    tbl.setRowHeight(30);
        tbl.setGridColor(new Color(25, 25, 112));
        tbl.setBackground(new Color(250, 235, 215));
        tbl.setForeground(new Color(0, 0, 0));
        tbl.setAutoCreateRowSorter(true);
        
        Action delete = new AbstractAction()
        {
            public void actionPerformed(ActionEvent e)
            {
                JTable table = (JTable)e.getSource();
                int modelRow = Integer.valueOf( e.getActionCommand() );
                Submit submit=new Submit();
                submit.setActionLevel((String)((MyTableModelForKitchen)table.getModel()).getValueAt(modelRow, 5));
                submit.setComments((String)((MyTableModelForKitchen)table.getModel()).getValueAt(modelRow, 6));
                submit.setExtra((String)((MyTableModelForKitchen)table.getModel()).getValueAt(modelRow, 3));
                submit.setOrderId((String)((MyTableModelForKitchen)table.getModel()).getValueAt(modelRow, 9));
                submit.setRecipe((String)((MyTableModelForKitchen)table.getModel()).getValueAt(modelRow, 2));
                submit.setSouce((String)((MyTableModelForKitchen)table.getModel()).getValueAt(modelRow, 4));
                MessageSubmitFire msg=new MessageSubmitFire(submit);
        		try {
        			mainMenu.ms.client.sendToServer(msg);
        			MessageSavingReply result = (MessageSavingReply)mainMenu.ms.client.GetMessage();
        			if(result.getResult()==0)  JOptionPane.showMessageDialog(null,"בעיית תקשורת pfKitchen");
        			
        		}catch (IOException ei) {
        			// TODO Auto-generated catch block
        			ei.printStackTrace();
        		}
             
            }
        };

        ButtonColumn buttonColumn = new ButtonColumn(tbl, delete, 0);
        buttonColumn.setMnemonic(KeyEvent.VK_D);
        
		JScrollPane scroll=new JScrollPane(tbl);
		tblPanel.add(scroll, BorderLayout.CENTER);
		return tblPanel;
	}
	
	
	private JPanel getOptionsPanel()
	{
		JPanel optionsPanel=new JPanel();
		optionsPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "אפשרויות", TitledBorder.CENTER, TitledBorder.TOP, null, new Color(0, 0, 0)));
		String [] seconds={"0","10","15","30","60","120"};
		comboBox=new JComboBox(seconds);
		comboBox.setSelectedItem("0");
		threadFlag=0;                          // zaplatka dlia threada
		comboBox.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
		comboBox.setFont( new Font( "Arial" , Font.BOLD, x/100 ));
		comboBox.setPreferredSize(new Dimension(x/15,y/20));
		comboBox.addActionListener(new java.awt.event.ActionListener() 
	  	{
			public void actionPerformed(java.awt.event.ActionEvent e) {
				
				JComboBox comboBox = (JComboBox)e.getSource();
			    String selectedSeconds = (String)comboBox.getSelectedItem(); 
			    if(selectedSeconds.equals("0"))  // for kill thread
			    {
			    	threadFlag=0;
			    }
			    else
			    {
			    	if(threadFlag==0)             // if the thread doesn't works
			    	{
			    		threadFlag=1;
			    		Thread fireStatus =new Thread(new FireStatus(thisPanel));
			    		fireStatus.setDaemon(true);
			    		fireStatus.start();
			    		
			    	}
			    	
			    }
				} 
		});
		optionsPanel.add(comboBox);		
		
		Icon refreshIcon = new ImageIcon("refresh-icon.png");
		Image img = ((ImageIcon) refreshIcon).getImage();
		Image newimg = img.getScaledInstance(x/30, y/20,java.awt.Image.SCALE_SMOOTH);
		refreshIcon = new ImageIcon(newimg);
		JButton butRetrieve=new JButton("רענן",refreshIcon);
		butRetrieve.addActionListener(new java.awt.event.ActionListener() 
		   {
			public void actionPerformed(java.awt.event.ActionEvent e) 
			{						
		    		Thread fireStatus =new Thread(new FireStatusForRefreshButton(thisPanel));
		    		fireStatus.setDaemon(true);
		    		fireStatus.start();								
			}
		});
		butRetrieve.setFont( new Font( "Arial" , Font.BOLD, x/100 ));
		butRetrieve.setPreferredSize(new Dimension(x/12,y/12));
		optionsPanel.add(butRetrieve);
		
		return optionsPanel;
	}
	
	
	
	
	private Vector<Vector> vecFiresToVecVec(Vector<Fire> vecFires)
	{
		Vector<Vector> vecvec=new Vector<Vector>();
		JButton but=new JButton("new");
		for(int i=0;i<vecFires.size();i++)
		{
			Fire fire = vecFires.get(i);
			Vector<Object> vecStr=new Vector<Object>();
			
			vecStr.add("");
			vecStr.add(fire.getTableNo());
			vecStr.add(fire.getRecipeName());
			vecStr.add(fire.getExtra().getName());
			vecStr.add(fire.getSouce().getName());
			vecStr.add(fire.getActionLevel());
			vecStr.add(fire.getComments());
			vecStr.add(fire.getWaiterName());
			vecStr.add(getWaitingTimeInMinuts(fire.getTimeOfFire()));
			vecStr.add(fire.getOrderId());
			vecStr.add(fire.getQuantity());
			vecvec.add(vecStr);		
			
		}		
		return vecvec;
	}
	
	
	
	private String getWaitingTimeInMinuts(String timeStr)
	{
		Calendar cal = Calendar.getInstance();		
		int hour=Integer.parseInt(timeStr.substring(0, 2));
	    int minute=Integer.parseInt(timeStr.substring(3, 5));
		int second=Integer.parseInt(timeStr.substring(6, 8));	
		
		DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");		
		Date date = new Date();		
		String curTime=timeFormat.format(date);
		int curHour=Integer.parseInt(curTime.substring(0, 2));
	    int curMinuts=Integer.parseInt(curTime.substring(3, 5));
		int curSec=Integer.parseInt(curTime.substring(6, 8));		
		
		cal.clear();		
		cal.set(Calendar.HOUR_OF_DAY,hour);
		cal.set(Calendar.MINUTE,minute);
		cal.set(Calendar.SECOND,second);
		cal.set(Calendar.MILLISECOND,0);
		
		Calendar calCurrent=Calendar.getInstance();	
		calCurrent.clear();		
		calCurrent.set(Calendar.HOUR_OF_DAY,curHour);
		calCurrent.set(Calendar.MINUTE,curMinuts);
		calCurrent.set(Calendar.SECOND,curSec);
		calCurrent.set(Calendar.MILLISECOND,0);
		
		long time1 = calCurrent.getTimeInMillis();
        long time2 = cal.getTimeInMillis();
        int result= (int)Math.abs(time1 - time2)/60000;
        return Integer.toString(result);
	}
		

	
	
	
	
	@Override
	public void tableChanged(TableModelEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	
	

	
	
	
	
	
// class for REFRESH Button Thread 
// the Thread makes only one single action
	
	private class FireStatusForRefreshButton implements Runnable{		
		private JPanel panel;
		private MessageGetFiredRecipesReply result;
		
		FireStatusForRefreshButton (JPanel p)
		{
			panel=p;
		}		
		
		
		final Runnable getMessage = new Runnable() {
			public void run() 
			{
				MessageGetFiredRecipes msg=new MessageGetFiredRecipes();				
				try {
					mainMenu.ms.client.sendToServer(msg);
					result = (MessageGetFiredRecipesReply)mainMenu.ms.client.GetMessage();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					result=null;
					System.out.println("in catch FireStatus 1");
				}
				
			}
			};
		
		
		
		
		
		public void run()
		{
				if (panel.isVisible()==false )
				{
					return;
				}
				
				try {
					SwingUtilities.invokeAndWait(getMessage);
					}
					catch (Exception e) {
					e.printStackTrace();
					System.out.println("in catch FireStatus 2");					
					}
				
					fires=result.getFires();
					int vecSize=fires.size();
					int vecButtonsSize=vecButtons.size();
					for(int i=0;i<vecButtonsSize;i++)
					{
						int minutsFromFirstFire=-1;
						int indexOfOrderedTable=(-1);
						for(int k=0;k<vecSize;k++)
						{
							int tableNo=Integer.parseInt(fires.get(k).getTableNo());
							if(tableNo==i+1)
							{
								int minutsFromFirstFireTemp=Integer.parseInt(getWaitingTimeInMinuts(fires.get(k).getTimeOfFire()));
								if(minutsFromFirstFire<minutsFromFirstFireTemp)
								{
								indexOfOrderedTable=k;
								break;
								}
							}
						}
						
							if(indexOfOrderedTable>-1)   // if table number i+1 is ordered 
							{							
						        String result2=getWaitingTimeInMinuts(fires.get(indexOfOrderedTable).getTimeOfFire());
						        vecButtons.get(i).setMinutsFromFirstFire(result2);
								vecButtons.get(i).setStatusFired();
								vecButtons.get(i).setNameOfOfficiant(fires.get(indexOfOrderedTable).getWaiterName());								
							}
							
							else
							{								
								vecButtons.get(i).cleanButton();															
							}
																		
					}
		}		
	}
	
	
	
	
	
	
	
// class for main Thread that updates the screen each 10,15,30,60,120 seconds	
	
	private class FireStatus implements Runnable{
		
		private JPanel panel;
		private MessageGetFiredRecipesReply result;
		
		FireStatus (JPanel p)
		{
			panel=p;
		}
		
		
		
		
		final Runnable getMessage = new Runnable() {
			public void run() 
			{
				MessageGetFiredRecipes msg=new MessageGetFiredRecipes();				
				try {
					mainMenu.ms.client.sendToServer(msg);
					result = (MessageGetFiredRecipesReply)mainMenu.ms.client.GetMessage();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					result=null;
					System.out.println("in catch FireStatus 1");
				}
				
			}
			};
		
		
		
		
		
		public void run()
		{
			int j=0;
			while(j==0)
			{
				if (panel.isVisible()==false || threadFlag==0)
				{
					threadFlag=0;
					return;
				}
				
				try {
					SwingUtilities.invokeAndWait(getMessage);
					}
					catch (Exception e) {
					e.printStackTrace();
					System.out.println("in catch FireStatus 2");					
					}
				
					fires=result.getFires();
					int vecSize=fires.size();
					int vecButtonsSize=vecButtons.size();
					for(int i=0;i<vecButtonsSize;i++)
					{
						int minutsFromFirstFire=-1;
						int indexOfOrderedTable=(-1);
						for(int k=0;k<vecSize;k++)
						{
							int tableNo=Integer.parseInt(fires.get(k).getTableNo());
							if(tableNo==i+1)
							{
								int minutsFromFirstFireTemp=Integer.parseInt(getWaitingTimeInMinuts(fires.get(k).getTimeOfFire()));
								if(minutsFromFirstFire<minutsFromFirstFireTemp)
								{
								indexOfOrderedTable=k;
								break;
								}
							}
						}
						
							if(indexOfOrderedTable>-1)   // if table number i+1 is ordered 
							{							
						        String result2=getWaitingTimeInMinuts(fires.get(indexOfOrderedTable).getTimeOfFire());
						        vecButtons.get(i).setMinutsFromFirstFire(result2);
								vecButtons.get(i).setStatusFired();
								vecButtons.get(i).setNameOfOfficiant(fires.get(indexOfOrderedTable).getWaiterName());								
							}
							
							else
							{							
								vecButtons.get(i).cleanButton();														
							}
																		
					}
					int secundsComboBox=Integer.parseInt((String)comboBox.getSelectedItem());
					try {
						Thread.sleep(secundsComboBox*1000);   //sleep 5 sec
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						System.out.println("in catch FireStatus 3");
					}              
			}
		}
	}
}
